package com.novunda.platform.common.dialects.shiro.processor;

import com.novunda.platform.common.dialects.shiro.ShiroFacade;
import org.thymeleaf.context.ITemplateContext;
import org.thymeleaf.engine.AttributeName;
import org.thymeleaf.model.IProcessableElementTag;
import org.thymeleaf.processor.element.IElementTagStructureHandler;
import org.thymeleaf.templatemode.TemplateMode;

/**
 * 有权限
 * @author linfeng
 * @since 2016/9/9
 */
public class HasPermissionAttributeProcessor extends AbstractAttributeProcessor {

    private static final String ATTR_NAME = "has-permission";
    private static final int PRECEDENCE = 1200;

    public HasPermissionAttributeProcessor(final String dialectPrefix) {
        super(TemplateMode.HTML, // This processor will apply only to HTML mode
                dialectPrefix,     // Prefix to be applied to name for matching
                null,              // No tag name: match any tag name
                false,             // No prefix to be applied to tag name
                ATTR_NAME,         // Name of the attribute that will be matched
                true,              // Apply dialect prefix to attribute name
                PRECEDENCE,        // Precedence (inside dialect's precedence)
                true);             // Remove the matched attribute afterwards
    }


    @Override
    protected void doShiroHandler(ITemplateContext context, IProcessableElementTag tag, AttributeName attributeName,
            String attributeValue, IElementTagStructureHandler structureHandler) {

        if (!ShiroFacade.hasPermission(attributeValue)) {
            structureHandler.removeElement();
        }

    }
}
